$.extend({
	client: function (data) {
		$.ajax(data);
	}
});

var Rest = function () {
	var makeparamsstring = function (arr) {
		var res = '';
		for (var k in arr) {
			if (res != '') res += '&';
			res += k + "=" + arr[k];
		}
		return res;
	}
	
	var prepareRequest = function (args) {
		args.url = 'ajax/' + args.method + args.resource.replace(/^ajax/, '');
		args.method = 'GET';
		if (args.params != null)
			args.data = makeparamsstring(args.params);
		
		return args;
	}
	
	return {
		get: function (args) {
			args.method = 'GET';
			args = prepareRequest(args);
			$.client(args);
		},
		put: function (args) {
			args.method = 'PUT';
			args.async = false;
			args = prepareRequest(args);
			$.client(args);
		},
		delete: function (args) {
			args.method = 'DELETE';
			args.async = false;
			args = prepareRequest(args);
			$.client(args);
		},
	};
}();

function nettoyer_grille () {
	$('.player').each(function () {
		$(this).html('');
	});
	
	$('.move').each(function () {
		$(this).unbind();
		$(this).removeClass('move');
		$(this).removeClass('jumpp1');
		$(this).removeClass('jumpp2');
		$(this).addClass('empty');
	});
}

function select_p (x, y) {
	if (!$('#' + x + '_' + y).hasClass('player')) {
		$('.player').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)
			.fadeOut(100).fadeIn(100);
	} else {
		if ($('#' + x + '_' + y).html() != '') {
			nettoyer_grille();
		} else {
			nettoyer_grille();
			
			Rest.get({
				'resource': "ajax/couppossibles",
				'params': {'x': x , 'y': y},
				'success': function(msg){
					$('.move').each(function (e) {
						e.removeClass('move');
					});
					eval(msg);
				}
			});
		}
	}
}

function tous (x, y) {
	nettoyer_grille();
	
	Rest.get({
		'resource': "ajax/couppossibles",
		'success': function(msg) {
			$('.move').each(function (e) {
				e.removeClass('move');
			});
			eval(msg);
		}
	});
}

function jouer_coup (xorig, yorig, xdest, ydest) {
	Rest.put({
		'resource': "ajax/coup",
		'params': {'xorig': xorig , 'yorig': yorig, 'xdest': xdest, 'ydest': ydest}
	});
	
	get_ajax_grille();
}

function get_ajax_grille () {
	Rest.get({
		'resource': "ajax/grille",
		'success': function(msg) {
			eval(msg);
		}
	});
	
	if ($('#joueur_' + current_player + '_auto').text() == 'X') {
		Rest.put({
			'resource': "ajax/meilleurcoup",
		});
	}
}

function toggle_auto (player_id) {
	if ($('#joueur_' + player_id + '_auto').text() == 'X') {
		$('#joueur_' + player_id + '_auto').text(' ');
	} else {
		$('#joueur_' + player_id + '_auto').text('X');
	}
	
	//~ get_ajax_grille();
}

function reset () {
	current_player = 0;
	Rest.delete({
		'resource': "ajax/grille",
	});
}

function select_p (x, y) {
	if ($('#' + x + '_' + y).html() == '') {
		Rest.get({
			'resource': "ajax/couppossibles",
			'params': {'x': x , 'y': y},
			'success': function(msg){
				$('.move').each(function (e) {
					e.removeClass('move');
				});
				eval(msg);
			}
		});
	}
}
